﻿using System.Security.Cryptography;
using System.Text;

namespace Tools
{
    /// <summary>
    /// 加密解密
    /// </summary>
    public class MakeEncryption
    {
        /// <summary>
        /// 获取MD5值
        /// </summary>
        /// <param name="_str"></param>
        /// <returns></returns>
        public static string Md5(string _str, string format = "x", Encoding encoding = null)
        {
            if (encoding == null)
                encoding = Encoding.Unicode;
            //MD5加密
            var md5 = MD5.Create();
            var bs = md5.ComputeHash(encoding.GetBytes(_str));
            var sb = new StringBuilder();
            foreach (byte b in bs)
            {
                sb.Append(b.ToString(format));
            }
            //所有字符转为大写
            return sb.ToString().ToUpper();
        }

        public static string Sha1(string secWebSocketKey)
        {
            byte[] pwBytes = Encoding.UTF8.GetBytes(secWebSocketKey);
            byte[] hash = SHA1.Create().ComputeHash(pwBytes);
            StringBuilder hex = new StringBuilder();
            for (int i = 0; i < hash.Length; i++) hex.Append(hash[i].ToString("X2"));

            return hex.ToString().ToLower();
        }
    }
}